import { HttpException, Injectable } from '@nestjs/common';
import { CreateAdminDto } from '../dto/create-admin.dto';
import { UpdateAdminDto } from '../dto/update-admin.dto';
import { Admin } from '../entity/admin.entity';
import * as argon2 from 'argon2';
import { JwtService } from '@nestjs/jwt';
import { LoggerService } from 'src/common/logger/logger.service';
import { Permission } from 'src/entity/permission.entity';
import { In } from 'typeorm';
import { AdminLoginDto } from 'src/dto/login-admin.dto';

@Injectable()
export class AdminService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly logger: LoggerService,
  ) {}

  async create(createAdminDto: CreateAdminDto) {
    let password = await argon2.hash('111111');

    return Admin.save({
      username: createAdminDto.username,
      password,
    });
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Admin.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      relations: ['permissions'],
    });

    return { list, count };
  }

  findOne(id: number) {
    return Admin.findOneBy({ id });
  }

  async update(id: number, updateAdminDto: UpdateAdminDto) {
    return Admin.update(id, { ...updateAdminDto });
  }

  remove(id: number) {
    return Admin.update(id, { deleteTime: new Date() });
  }

  /** 生成token */
  private generateToken({ id }: Admin) {
    this.logger.log('生成token:' + id);

    return {
      token: this.jwtService.sign(
        {
          id,
        },
        { secret: process.env.ADMIN_SECRET },
      ),
    };
  }

  async login(adminLoginDto: AdminLoginDto) {
    if (!adminLoginDto.username || !adminLoginDto.password) {
      throw new HttpException('登录失败', 400);
    }

    let admin = await Admin.findOneBy({ username: adminLoginDto.username });

    if (admin == null) {
      throw new HttpException('登录失败', 400);
    }

    if (await argon2.verify(admin.password, adminLoginDto.password)) {
      let token = this.generateToken(admin);
      return token;
    }

    throw new HttpException('登录失败', 400);
  }

  async resetPassword(id: number) {
    let admin = await Admin.findOne({ where: { id } });
    admin.password = await argon2.hash('111111');
    return admin.save();
  }

  async bindPermissions(adminId: number, permissions: any) {
    let admin = await Admin.findOne({ where: { id: adminId } });

    // 查询所有权限
    let permissionList = await Permission.find({
      where: { id: In(permissions) },
    });

    admin.permissions = permissionList;

    return admin.save();
  }

  async menus(uid: number) {
    // if (uid == 1) {
    //   let menus = await Permission.find({
    //     where: { type: 1 },
    //   });

    //   return menus;
    // }

    let admin = await Admin.findOne({
      where: { id: uid },
      relations: ['permissions'],
    });

    let menus = admin.permissions.filter((item) => item.type == 1);
    this.logger.log(JSON.stringify(menus));

    return menus;
  }
}
